import java.io.*;
import java.util.Iterator;
import java.util.Map;

/**
 * @author by zyl
 * @date 2020/3/28.
 */
public class FileUtil {
    /**
     * Writes a set of key-value pairs to a file
     * @param tableName
     * @param keyValues
     */
    public static void writeLine(String tableName, Map<String,String> keyValues){
        try{
            FileWriter fw = new FileWriter(tableName, true);
            BufferedWriter bw = new BufferedWriter(fw);
            Iterator<Map.Entry<String,String>> iter=keyValues.entrySet().iterator();
            while(iter.hasNext()){
                Map.Entry<String,String> entrys=iter.next();
                String key=entrys.getKey();
                String values=entrys.getValue();
                String line=key+" "+values;
                bw.write(line);
                bw.newLine();
            }
            bw.flush();
            bw.close();
            fw.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * Returns the corresponding text content based on the sequence number
     * @param tableName
     * @param tag
     * @return
     */
    public static String readTag(String tableName,String tag){
        String result="";
        try{
            BufferedReader br = new BufferedReader(new FileReader(tableName));
            String line=null;
            while((line=br.readLine())!=null) {
                String[] lines=line.split(" ");
                if(lines[0].equals(tag))
                    result=line;
            }
            br.close();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Find if the corresponding ID is included
     * @param ID
     * @return
     */
    public static String readID(String ID){
        String result="";
        try{
            BufferedReader br = new BufferedReader(new FileReader(CommonValue.IDTable));
            String line=null;
            while((line=br.readLine())!=null) {
                String[] lines=line.split(" ");
                if(lines[1].equals(ID))
                    result=line;
            }
            br.close();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        return result;
    }
}